package com.cloudwave.trailends.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;


public class DateUtils implements DateFormator {


	public static Date now() {
		return new GregorianCalendar().getTime();
	}
	public static Date now(long time) {
		Calendar c = new GregorianCalendar();
		c.setTimeInMillis(time);
		return c.getTime();
	}
	public static String now(String pattern) {
		Date date = DateUtils.now();
		return DateUtils.format(date, pattern);
	}
	public static String nowDate() {
		Date date = DateUtils.now();
		return DateUtils.format(date, DateUtils.YEAR_MONTH_DAY);
	}
	public static String nowDateTime() {
		Date date = DateUtils.now();
		return DateUtils.format(date, DateUtils.YEAR_MONTH_DAY_HH_MM_SS);
	}
	
	public static int nowYear() {
		return new GregorianCalendar().get(Calendar.YEAR);
	}
	public static int nowMonth() {
		return new GregorianCalendar().get(Calendar.MONTH) + 1;
	}
	public static int nowDay() {
		return new GregorianCalendar().get(Calendar.DAY_OF_MONTH);
	}
	public static long nowTimestamp() {
		return new GregorianCalendar().getTimeInMillis();
	}
	
	public static Date parseDay(String time) {
		return CalendarUtils.toCalendar(time, YEAR_MONTH_DAY).getTime();
	}
	
	public static Date parseDayTime(String time) {
		return CalendarUtils.toCalendar(time, YEAR_MONTH_DAY_HH_MM_SS).getTime();
	}
	
	public static Date parseDate(int year, int month, int day) {
		Calendar c = new GregorianCalendar();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month);
		c.set(Calendar.DAY_OF_MONTH, day);
		return c.getTime();
	}
	
	public static Date parseDate(int year, int month, int day, int hour, int minute, int second) {
		Calendar c = new GregorianCalendar();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month - 1);
		c.set(Calendar.DAY_OF_MONTH, day);
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minute);
		c.set(Calendar.SECOND, second);
		
		return c.getTime();
	}
	
	public static Date parseDate(String time, String pattern) {
		return CalendarUtils.toCalendar(time, pattern).getTime();
	}

	/**
	 * 提供从String类型到Date类型的类型转化，目前自动支持 "yyyy-MM-dd"、"yyyy-MM"、 "yyyy-MM-dd
	 * HH:mm:ss"、"MM-dd"等4种日期格式的自动转化
	 * @param time
	 * @return
	 */
	public static Date parseDate(String time) {
		for (String key : defaultDateFormatMap.keySet()) {
			if (isDateFormat(time, key)) {
				return DateUtils.parseDate(time, defaultDateFormatMap.get(key));
			}
		}
		throw new RuntimeException("just support format : "
				+ StringUtils.collectionToDelimitedString(defaultDateFormatMap
						.values(), ",") + " - " + time);
	}

	@SuppressLint("SimpleDateFormat")
	public static String format(String pattern) {
		if (pattern == null || pattern.length() == 0) {
			pattern = YEAR_MONTH_DAY;
		}
		DateFormat df = new SimpleDateFormat(pattern);
		return df.format(new GregorianCalendar().getTime());
	}
	@SuppressLint("SimpleDateFormat")
	public static String format(long time, String pattern) {
		DateFormat df = new SimpleDateFormat(pattern);
		Date date = new Date(time);
		return df.format(date);
	}
	@SuppressLint("SimpleDateFormat")
	public static String format(Date date) {
		DateFormat df = new SimpleDateFormat(YEAR_MONTH_DAY);
		return df.format(date);
	}
	@SuppressLint("SimpleDateFormat")
	public static String formatDate(Date date) {
		DateFormat df = new SimpleDateFormat(YEAR_MONTH_DAY);
		return df.format(date);
	}
	@SuppressLint("SimpleDateFormat")
	public static String formatTime(Date date) {
		DateFormat df = new SimpleDateFormat(YEAR_MONTH_DAY_HH_MM_SS);
		return df.format(date);
	}
	@SuppressLint("SimpleDateFormat")
	public static String format(Date date, String pattern) {
		if (pattern == null) {
			pattern = YEAR_MONTH_DAY;
		}
		DateFormat df = new SimpleDateFormat(pattern);
		return df.format(date);
	}
	public static String localFormatDate(long time) {
		Calendar c = new GregorianCalendar();
		c.setTime(new Date(time));
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		StringBuffer sb = new StringBuffer(10);
		sb.append(year).append("年").append(month).append("月").append(day).append("日");
		return sb.toString();
	}
	
	public static String localFormatTime(long time) {
		Calendar c = new GregorianCalendar();
		c.setTime(new Date(time));
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		StringBuffer sb = new StringBuffer(10);
		sb.append(year).append("年").append(month).append("月").append(day).append("日");
		return sb.toString();
	}
	
	public static String localFormatDateTime(long time) {
		Calendar c = new GregorianCalendar();
		c.setTime(new Date(time));
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		StringBuffer sb = new StringBuffer(10);
		sb.append(year).append("年").append(month).append("月").append(day).append("日");
		return sb.toString();
	}
	
	
	
	
	/**
	 * 微博 格式化输出时间
	 * @param time
	 * @return
	 */
	public static String weiboFormat(long time) {
		Calendar dTrueTime = new GregorianCalendar();
        dTrueTime.setTimeInMillis(time);
        
		Calendar dNow = new GregorianCalendar();
		long iNow = dNow.getTimeInMillis();
		String ret = "-";
		if (time > iNow) {
			ret = "您穿越了...";
		} else if (time > iNow - ONE_SECOND * 10) {
			ret = "刚刚";
		} else if (time > iNow - ONE_MINUTE) {
			// e.g. 30秒前
			ret = ((iNow - time) / ONE_SECOND / 10) + "0秒前";
		} else if (time > iNow - ONE_HOUR) {
			// e.g. 3分钟前
			ret = ((iNow - time) / ONE_MINUTE) + "分钟前";
		} else if (time > iNow - ONE_DAY) {
			// e.g. 今天11:39
			ret = "今天" + dTrueTime.get(Calendar.HOUR_OF_DAY) + ":" + dTrueTime.get(Calendar.MINUTE);
		} else {
	        if(dTrueTime.get(Calendar.YEAR) == dNow.get(Calendar.YEAR)){
	            // e.g. 9月10日 07:50
	            ret = (dTrueTime.get(Calendar.MONTH)+1) + "月" + dTrueTime.get(Calendar.DATE) + "日 " + dTrueTime.get(Calendar.HOUR_OF_DAY) + ":" + dTrueTime.get(Calendar.MINUTE);
	        }else{
	            // e.g. 2011年2月3日 12:39
	            ret = dTrueTime.get(Calendar.YEAR) + "年" + (dTrueTime.get(Calendar.MONTH)+1) + "月" + dTrueTime.get(Calendar.DATE) + "日 " + dTrueTime.get(Calendar.HOUR_OF_DAY) + ":" + dTrueTime.get(Calendar.MINUTE);
	        }
	    }
		
		return ret;
	}
	
	public static String weiboFormat(Date date) {
		Calendar dTrueTime = new GregorianCalendar();
		dTrueTime.setTime(date);
		return weiboFormat(dTrueTime.getTimeInMillis());
		
	}
	
	public static String weiboFormat(String date) {
		return weiboFormat(parseDate(date).getTime());
	}
	
	/**
	 * 计算耗时
	 * @param elapsed 毫秒
	 * @return
	 */
	public static int[] duration(long elapsed) {
		int h = (int)  (elapsed / (1000 * 60 * 60));
		int l1 = (int) (elapsed - h * (1000 * 60 * 60));
		int m = (int) (l1 / (1000 * 60));
		int l2 = (int) (l1 - (m * 1000 * 60));
		int s = l2 / 1000;
		int mm = l2 % 1000;
		int[] result = new int[] {0, h, m, s, mm};
		return result;
	}
	
	public static void main(String[] args) {
		
		System.out.println(weiboFormat(1398522769723l));
	}
	
	

	/**
	 * 比较两个 Date 对象表示的时间值（从历元至现在的毫秒偏移量）。
	 * 
	 * @param d1
	 * @param d2
	 * @return 如果 d1 表示的时间等于 d2 表示的时间，则返回 0 值；如果此 d1 的时间在d2表示的时间之前，则返回小于 0 的值；如果
	 *         d1 的时间在 d2 表示的时间之后，则返回大于 0 的值。
	 * 
	 */
	public static int compareDateTime(Date d1, Date d2) {

		Calendar c1 = new GregorianCalendar();
		Calendar c2 = new GregorianCalendar();
		c1.setTime(d1);
		c2.setTime(d2);

		return c1.compareTo(c2);
	}

	/**
	 * 比较两个 Date 对象表示的日期值（仅仅比较日期,忽略时分秒）。 -wuwm
	 * 
	 * @param d1
	 * @param d2
	 * @return 如果 d1 表示的日期等于 d2 表示的日期，则返回 0 值；如果此 d1 的日期在d2表示的日期之前，则返回小于 0 的值；如果
	 *         d1 的日期在 d2 表示的日期之后，则返回大于 0 的值。
	 * 
	 */
	public static int compareDate(Date d1, Date d2) {

		d1 = DateUtils.parseDate(DateUtils.format(d1, DateUtils.YEAR_MONTH_DAY),
				DateUtils.YEAR_MONTH_DAY);
		d2 = DateUtils.parseDate(DateUtils.format(d2, DateUtils.YEAR_MONTH_DAY),
				DateUtils.YEAR_MONTH_DAY);
		Calendar c1 = new GregorianCalendar();
		Calendar c2 = new GregorianCalendar();
		c1.setTime(d1);
		c2.setTime(d2);

		return c1.compareTo(c2);
	}

	/**
	 * 根据年月获取一个月的开始时间（第一天的凌晨）
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static Date beginTimeOfMonth(int year, int month) {
		Calendar first = new GregorianCalendar(year, month - 1, 1, 0, 0, 0);
		return first.getTime();
	}

	/**
	 * 根据年月获取一个月的结束时间（最后一天的最后一毫秒）
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static Date endTimeOfMonth(int year, int month) {
		Calendar first = new GregorianCalendar(year, month, 1, 0, 0, 0);
		first.add(Calendar.MILLISECOND, -1);
		return first.getTime();
	}

	/**
	 * 获取前preDays天的Date对象
	 * 
	 * @param date
	 * @param preDays
	 * @return
	 */
	public static Date preDays(Date date, int preDays) {
		GregorianCalendar c1 = new GregorianCalendar();
		c1.setTime(date);
		GregorianCalendar cloneCalendar = (GregorianCalendar) c1.clone();
		cloneCalendar.add(Calendar.DATE, -preDays);
		return cloneCalendar.getTime();
	}

	/**
	 * 获取后nextDays天的Date对象
	 * 
	 * @param date
	 * @param nextDays
	 * @return
	 */
	public static Date nextDays(Date date, int nextDays) {
		GregorianCalendar c1 = new GregorianCalendar();
		c1.setTime(date);
		GregorianCalendar cloneCalendar = (GregorianCalendar) c1.clone();
		cloneCalendar.add(Calendar.DATE, nextDays);
		return cloneCalendar.getTime();
	}

	public static Date nextMonths(Date date, int nextMonth) {
		GregorianCalendar c1 = new GregorianCalendar();
		c1.setTime(date);
		GregorianCalendar cloneCalendar = (GregorianCalendar) c1.clone();
		cloneCalendar.add(Calendar.MONTH, nextMonth);
		return cloneCalendar.getTime();
	}

	public static Date preMonths(Date date, int preMonth) {
		GregorianCalendar c1 = new GregorianCalendar();
		c1.setTime(date);
		GregorianCalendar cloneCalendar = (GregorianCalendar) c1.clone();
		cloneCalendar.add(Calendar.MONTH, -preMonth);
		return cloneCalendar.getTime();
	}

	public static long getDiffMillis(Date d1, Date d2) {
		long diff = d1.getTime() - d2.getTime();
		return diff;
	}

	/**
	 * 间隔天数
	 * 
	 * @param d1
	 * @param d2
	 * @return d1 - d2 实际天数,如果 d1 表示的时间等于 d2 表示的时间，则返回 0 值；如果此 d1
	 *         的时间在d2表示的时间之前，则返回小于 0 的值；如果 d1 的时间在 d2 表示的时间之后，则返回大于 0 的值。
	 */
	public static long dayDiff(Date d1, Date d2) {
		Calendar c1 = new GregorianCalendar();
		Calendar c2 = new GregorianCalendar();

		c1.setTime(d1);
		c2.setTime(d2);

		long diffDays = CalendarUtils.getDiffDays(c1, c2);

		return diffDays;
	}

	/**
	 * 获取间隔时间
	 * 
	 * @param d1
	 * @param d2
	 * @return HH:MM:SS,返回时间间隔的绝对值，没有负数
	 */
	public static String getDiffs(Date d1, Date d2) {
		long diffMillis = DateUtils.getDiffMillis(d1, d2);
		long diffHours = diffMillis / (60L * 60L * 1000L);
		long diffMinutes = diffMillis / (60L * 1000L) % 60;
		long diffSeconds = (diffMillis / 1000L) % 60;
		diffHours = Math.abs(diffHours);
		diffMinutes = Math.abs(diffMinutes);
		diffSeconds = Math.abs(diffSeconds);
		StringBuffer temp = new StringBuffer();
		temp.append(diffHours < 10 ? "0" + diffHours : diffHours);
		temp.append(":");
		temp.append(diffMinutes < 10 ? "0" + diffMinutes : diffMinutes);
		temp.append(":");
		temp.append(diffSeconds < 10 ? "0" + diffSeconds : diffSeconds);
		return temp.toString();
	}

	public static boolean isDateFormat(String date) {
		for (String key : defaultDateFormatMap.keySet()) {
			if (isDateFormat(date, key)) {
				return true;
			}
		}
		return false;
	}

	public static boolean isDateFormat(String date, String format) {
		return StringUtils.isDefinedPattern(date, format);
	}

	/**
	 * 根据日期返回日期中的年. wuwm
	 * 
	 * @param d
	 * @return int
	 */
	public static int getYear(Date d) {
		String dateStr = DateUtils.format(d, DateUtils.YEAR_MONTH); // yyyy-MM
		return Integer.parseInt(dateStr.split(DateUtils.SPLIT_CHAR)[0]);
	}

	/**
	 * 根据日期返回日期中的年. wuwm
	 * 
	 * @param d
	 * @return int
	 */
	public static int getMonth(Date d) {
		String dateStr = DateUtils.format(d, DateUtils.YEAR_MONTH); // yyyy-MM
		return Integer.parseInt(dateStr.split(DateUtils.SPLIT_CHAR)[1]);
	}

	/**
	 * 根据日期返回日期中的日. wuwm
	 * 
	 * @param d
	 * @return int
	 */
	public static int getDay(Date d) {
		String dateStr = DateUtils.format(d, DateUtils.YEAR_MONTH_DAY); // yyyy-MM-dd
		return Integer.parseInt(dateStr.split(DateUtils.SPLIT_CHAR)[2]);
	}

	private static Map<String, String> defaultDateFormatMap = new HashMap<String, String>();
	static {
		defaultDateFormatMap.put("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}",
				DateUtils.YEAR_MONTH_DAY);
		defaultDateFormatMap
				.put("[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}", "yyyy/MM/dd");
		defaultDateFormatMap
				.put(
						"[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}",
						DateUtils.YEAR_MONTH_DAY_HH_MM_SS);
		defaultDateFormatMap
				.put(
						"[0-9]{4}/[0-9]{1,2}/[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}",
						"yyyy/MM/dd HH:mm:ss");
		defaultDateFormatMap.put("[0-9]{4}-[0-9]{1,2}", DateUtils.YEAR_MONTH);
		defaultDateFormatMap.put("[0-9]{4}/[0-9]{1,2}", "yyyy/MM");
	}
	
	/**
	 * 
	 * 判断两个日期是否是同年同月
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static boolean isSameYearMonth(Date d1, Date d2) {
		if(null == d1 || null == d2) return false;
		GregorianCalendar g1 = new GregorianCalendar();
		g1.setTime(d1);
		GregorianCalendar cloneCalendar = (GregorianCalendar) g1.clone();
		cloneCalendar.setTime(d2);
		if(g1.get(Calendar.YEAR) != cloneCalendar.get(Calendar.YEAR)) {
			return false;
		}
		if(g1.get(Calendar.MONTH) != cloneCalendar.get(Calendar.MONTH)) {
			return false;
		}
		return true;
	}
	public static Date addTimes(Date startTime, long times) {
		Calendar c = new GregorianCalendar();
		c.setTime(startTime);
		c.add(Calendar.SECOND, (int) times);
		return c.getTime();
	}
	

}
